import { Input, Toast } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { GetAndroidMenu, ToPay, GetUserInfo, GetIosMenu } from '../../api/mine'
import NavBar from '../../components/Navbar'
import appSdk from '../../utils/app_sdk'
import './index.less'
import { compareVersions, getAuthentication, getVersion, isIOS } from '../../utils/util'

const NavTab = ({ navigate }) => {
  return (
    <div className="nav_tab">
      <span className="active">{window.baseConfig.coin_name}</span>
      <span className="un" onClick={() => navigate('/income')}>
        我的收益
      </span>
    </div>
  )
}
const ua = navigator.userAgent.toLowerCase()
export default function Recharge() {
  const navigate = useNavigate()
  const [payWay, setPayWay] = useState('aliPay')
  const [userInfo, setUserInfo] = useState({ mizuan: 0, first_charge: 0, recharge_price: 0, is_idcard: 0 })
  const [goods, setGoods] = useState([{ price: 0, mizuan: 0, discount: 0, id: 0 }])
  const [selectGoods, setSelectGoods] = useState()
  const [inputMoney, setInputMoney] = useState()

  const [isAppstore, setIsAppstore] = useState(Boolean(getAuthentication('packageChannel')))

  const requestMenuInfo = (update = true) => {
    Toast.show({
      content: '加载中...',
      icon: 'loading',
      maskClickable: false
    })
    ;(isAppstore ? GetIosMenu() : GetAndroidMenu()).then((res) => {
      GetUserInfo()
        .then((result) => {
          setUserInfo({
            ...res.data,
            ...result.data
          })
          setGoods(res.data.goods)
          if (update) {
            setSelectGoods(res.data.goods[0].id)
          }
        })
        .finally(() => {
          Toast.clear()
        })
    })
  }

  useEffect(() => {
    if (window.baseConfig.package_key === 'ymeng') {
      navigate('/recharge_v2', { replace: true })
    }

    console.log('packageChannel =>', getAuthentication('packageChannel'))
    // setIsAppstore(getAuthentication('packageChannel'))
    requestMenuInfo(true)
    if (compareVersions(getVersion() || '1.0.0', '2.2.0') !== -1) {
      appSdk('setFullScreen', 0)
    }
  }, [])

  const onFocus = () => {
    setSelectGoods(0)
  }

  const payNow = () => {
    GetUserInfo().then((result) => {
      setUserInfo({
        ...userInfo,
        ...result.data
      })
      const price = goods?.find((item) => item.id === selectGoods)?.price || Number(inputMoney) / 10 || ''
      console.log(
        `最新 认证状态 is_idcard: ${result?.data.is_idcard}, is_fase_order: ${result.data.is_fase_order}，已充值金额 ${+result.data.recharge_price}, 待充值 ${price}`
      )
      if (!price) {
        Toast.show({
          content: '请选择要充值的金额',
          maskClickable: false
        })
        return false
      }
      const version = isIOS() ? '2.2.7' : '2.3.2'
      if (compareVersions(getVersion() || '1.0.0', version) !== -1) {
        // 当前版本小于可以拉支付版本
        // 未实名 并且大于500
        if (
          !(Number(result?.data.is_idcard) && result.data.is_fase_order) &&
          +result?.data.recharge_price + Number(price) >= 500 &&
          +result?.data.recharge_status === 0
        ) {
          Toast.show({
            content: '当前账户未实名~',
            maskClickable: false,
            duration: 2000
          })
          const type = Boolean(+result?.data.is_idcard) ? 2 : 1 // 能走到这说明只有两种情况 未实名未刷脸 或者 实名未刷脸
          appSdk('jumpToUserIdentity', type, (result) => {
            console.log('成功回调，拿到的参数是', result)
            if (typeof result === 'string') {
              const data = JSON.parse(result)
              Toast.show({
                icon: data.status === 'success' ? 'success' : 'fail',
                content: data.status === 'success' ? '认证成功' : data?.message || '认证失败',
                duration: 2000
              })
            }
            if (typeof result === 'object') {
              const data = result
              Toast.show({
                icon: data.status === 'success' ? 'success' : 'fail',
                content: data.status === 'success' ? '认证成功' : data?.message || '认证失败',
                duration: 2000
              })
            }
            // Toast.clear()
          })
          return false
        }
      }
      if (Number(price) >= 1) {
        requestPay()
      } else {
        Toast.show({
          content: '最少充值1元',
          maskClickable: false
        })
      }
    })
  }

  const requestPay = () => {
    Toast.show({
      icon: 'loading',
      content: '正在支付中，请勿重复提交...',
      maskClickable: false,
      duration: 3000
    })
    if (!isAppstore) {
      ToPay({
        goods_id: selectGoods ? selectGoods : null,
        type: payWay === 'aliPay' ? 1 : 2,
        device: /(android)/i.test(ua) ? 'Android' : 'IOS',
        price: selectGoods ? null : Number(inputMoney) / 10,
        user_id: userInfo.id
      })
        .then((res) => {
          console.log('支付信息', res.data)
          appSdk(payWay, res.data, (result) => {
            console.log('成功回调，拿到的参数是', result)
            requestMenuInfo(false)
            if (typeof result === 'string') {
              const data = JSON.parse(result)
              Toast.show({
                // icon: data.status === "success" ? "success" : "fail",
                content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
              })
            }
            if (typeof result === 'object') {
              const data = result
              Toast.show({
                // icon: data.status === "success" ? "success" : "fail",
                content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
              })
            }
          })
        })
        .finally(() => {
          Toast.clear()
        })
    } else {
      const good_id = goods?.find((item) => item.id === selectGoods)?.good_id || ''
      appSdk(
        'appStorePay',
        {
          id: selectGoods,
          good_id
        },
        (result) => {
          Toast.clear()
          console.log('appstore 成功回调，拿到的参数是', result)
          requestMenuInfo(false)
          if (typeof result === 'string') {
            const data = JSON.parse(result)
            Toast.show({
              // icon: data.status === "success" ? "success" : "fail",
              content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
            })
          }
          if (typeof result === 'object') {
            const data = result
            Toast.show({
              // icon: data.status === "success" ? "success" : "fail",
              content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
            })
          }
        }
      )
    }
  }

  return (
    <div className="recharge_wrap">
      <NavBar title={<NavTab navigate={navigate} />} other={<span onClick={() => navigate('/record_list?type=dou')}>明细</span>} />
      <div className="mine_wallet">
        <div className="flex_t">
          <div className="icon"></div>
          <div className="text">{window.baseConfig.coin_name}余额</div>
        </div>
        <div className="money">{+userInfo?.mizuan || 0}</div>
        <div className="bg"></div>
      </div>
      <div className={`recharge_menu`}>
        <div className="title">
          <span className="t">充值金额</span>
          <span className="tt">*严禁未成年人充值</span>
        </div>
        <div className="list">
          {goods.map((item, idx) => (
            <div
              className={`item ${selectGoods === item.id ? 'active' : ''}`}
              key={item.id + Math.random()}
              onClick={() => setSelectGoods(item.id)}
            >
              {idx === 0 && Number(userInfo.first_charge) === 0 ? (
                <div className="special_icon">
                  <span>首充优惠</span>
                </div>
              ) : null}
              <div className="coin_info">
                <div className="icon"></div>
                <div className="coin_num">{item.mizuan}</div>
              </div>
              {Number(userInfo.first_charge) === 0 ? <div className="send">赠送{item?.discount || 0}</div> : null}
              <div className="price">¥{item?.price || 0}</div>
            </div>
          ))}
        </div>
        <div className={`input_warp ${selectGoods === 0 ? 'active' : ''}`} style={{ display: isAppstore ? 'none' : '' }}>
          <div className="icon"></div>
          <div className="input">
            <Input
              onFocus={onFocus}
              onChange={(e) => {
                console.log(e)
                if (+e >= 99999) {
                  setInputMoney('99999')
                } else {
                  setInputMoney(Number(e).toFixed(0).replace(/^0+/g, ''))
                }
              }}
              min={1}
              max={99999}
              value={inputMoney}
              type="number"
              placeholder="请输入整数金额"
            />
          </div>
          {inputMoney && <div className="income">￥{Number(inputMoney) / 10}</div>}
        </div>
        <div className="pay_btns" style={{ display: isAppstore ? 'none' : '' }}>
          <div onClick={() => setPayWay('wechatPay')} className={`btn wechat ${payWay === 'wechatPay' ? 'active' : ''}`}>
            <div className="icon"></div>
            <div className="text">微信支付</div>
          </div>
          <div onClick={() => setPayWay('aliPay')} className={`btn ali ${payWay === 'aliPay' ? 'active' : ''}`}>
            <div className="icon"></div>
            <div className="text">支付宝支付</div>
          </div>
        </div>
        <div className="pay_info">
          <p className="tips tips_txt">
            {window.baseConfig.package_name}严禁未成年人进行充值，请阅读
            <a href={`${window.baseConfig.baseUrl}/protocol/dou_agreement`} style={{ color: '#AFFBA1', textDecoration: 'none' }}>
              《{window.baseConfig.package_name}充值协议》
            </a>
          </p>
          <div className="pay_btn" onClick={payNow}>
            立刻充值
          </div>
        </div>
      </div>
    </div>
  )
}
